# -*- coding: utf8 -*-

import pymysql
from pymysql.cursors import DictCursor


class Config(object):
    """Configure me so examples work

    Use me like this:

        mysql.connector.Connect(**Config.dbinfo())
    """

    HOST = 'localhost'
    DATABASE = 'duplicates'
    USER = 'duplicates'
    PASSWORD = 'LHACH7MuKcNxnedU'
    PORT = 3306

    CHARSET = 'utf8'
    UNICODE = True

    TIMEOUT_CON = 10

    @classmethod
    def dbinfo(cls):
        return {
            'host': cls.HOST,
            'port': cls.PORT,
            'db': cls.DATABASE,
            'user': cls.USER,
            'passwd': cls.PASSWORD,
            'charset': cls.CHARSET,
            'use_unicode': cls.UNICODE,
            'cursorclass': DictCursor,
            'connect_timeout': cls.TIMEOUT_CON
        }


class DataBase(object):

    _connection = None

    def getConnection( self, dbinfo=None ):
        if self._connection:
            try:
                if not self._connection.ping(True):
                    self._connection = None
            except:
                self._connection = None
                pass

        if not self._connection:
            config = Config.dbinfo().copy()
            if dbinfo and dbinfo is dict:
                config.update(dbinfo)
            self._connection = pymysql.connect(**config)
        return self._connection

    def getCursor(self):
        return self.getConnection().cursor()
